package org.jeecg.modules.wmhb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.mapper.WmContractMapper;
import org.jeecg.modules.wmhb.mapper.WmContractProductMapper;
import org.jeecg.modules.wmhb.mapper.WmPlanLogMapper;
import org.jeecg.modules.wmhb.mapper.WmPlanMapper;
import org.jeecg.modules.wmhb.service.IWmClientService;
import org.jeecg.modules.wmhb.service.IWmContractService;
import org.jeecg.modules.wmhb.service.IWmProjectService;
import org.jeecg.modules.wmhb.service.IWmVendorService;
import org.jeecg.modules.wmhb.vo.ContractVo;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 合同表
 * @Author: jeecg-boot
 * @Date:   2024-09-02
 * @Version: V1.0
 */
@Service
public class WmContractServiceImpl extends ServiceImpl<WmContractMapper, WmContract> implements IWmContractService {
    @Autowired
    private IWmProjectService wmProjectService;
    @Autowired
    private IWmClientService wmClientService;
    @Autowired
    private IWmVendorService wmVendorService;
    @Autowired
    private WmContractProductMapper contractProductMapper;
    @Autowired
    private WmPlanMapper planMapper;
    @Autowired
    private WmPlanLogMapper planLogMapper;

    @Override
    public String checkCodeUnique(WmContract wmContract){
        WmContract item = baseMapper.checkCodeUnique(wmContract);
        String itemId = wmContract.getId() == null ? "" : wmContract.getId();
        if(item != null && !itemId.equals(item.getId())){
            return UserConstant.NOT_UNIQUE;
        }else{
            return UserConstant.UNIQUE;
        }
    };

    @Override
    public String checkNameUnique(WmContract wmContract){
        WmContract item = baseMapper.checkNameUnique(wmContract);
        String itemId = wmContract.getId() == null ? "" : wmContract.getId();
        if(item != null && !itemId.equals(item.getId())){
            if(wmContract.getWmProjectId().equals(item.getWmProjectId())){
                return UserConstant.NOT_UNIQUE;
            }
            else{
                return UserConstant.UNIQUE;
            }
        }else{
            return UserConstant.UNIQUE;
        }
    };

    @Override
    public boolean checkHasItem(String id) {
        int num = baseMapper.hasItemById(id);
        return num >0 ? true:false;
    };

    @Override
    public List<WmContract> queryGantContractByWmProjectId(String wmProjectId){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmContract::getWmProjectId, wmProjectId).ne(WmContract::getStatus, UserConstant.CONTRACT_STATUS_PREPARE);
        return list(queryWrapper);
    };

    @Override
    public List<WmContract> confirmedContractList(){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.CONTRACT_STATUS_PREPARE);
        queryWrapper.notIn(WmContract::getStatus, statusList);
        return list(queryWrapper);
    };

    @Override
    public List<WmContract> searchByName(String searchKey){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(searchKey)) {
            queryWrapper.like(WmContract::getName, searchKey);
        }
        return list(queryWrapper);
    };

    @Override
    public List<WmContract> searchByProjectAndName(String wmProjectId, String searchKey){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmContract::getWmProjectId, wmProjectId);
        if(!StringUtils.isEmpty(searchKey)) {
            queryWrapper.like(WmContract::getName, searchKey);
        }
        return list(queryWrapper);
    };

    @Override
    public List<WmContract> listBySearch(WmContract wmContract){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(wmContract.getWmProjectId())){
            queryWrapper.eq(WmContract::getWmProjectId, wmContract.getWmProjectId());
        }
        if(!StringUtils.isEmpty(wmContract.getName())){
            queryWrapper.like(WmContract::getName, wmContract.getName());
        }
        if(!StringUtils.isEmpty(wmContract.getCode())){
            queryWrapper.like(WmContract::getCode, wmContract.getCode());
        }
        return list(queryWrapper);
    };

    @Override
    public ModelAndView exportContractExcel(HttpServletRequest request, List<WmContract> wmContractList){
        List<ContractVo> listOfSheet = new ArrayList<>();
        for(WmContract wmContract: wmContractList){
            ContractVo contractVo = new ContractVo();
            contractVo.setMoney(wmContract.getMoney());
            contractVo.setPrice(wmContract.getPrice());
            contractVo.setNoTaxMoney(wmContract.getNoTaxMoney());
            contractVo.setTax(wmContract.getTax());
            contractVo.setContractCode(wmContract.getCode());
            WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
            contractVo.setWmProjectName(wmProject.getName());
            if(!StringUtils.isEmpty(wmContract.getWmClientId())) {
                WmClient wmClient = wmClientService.getById(wmContract.getWmClientId());
                contractVo.setWmClientName(wmClient.getCnName());
            }

            if(!StringUtils.isEmpty(wmContract.getWmVendorId())) {
                WmVendor wmVendor = wmVendorService.getById(wmContract.getWmVendorId());
                contractVo.setWmVendorName(wmVendor.getCnName());
            }

            listOfSheet.add(contractVo);
        }

        // 2、添加sheet 的数据及其对应的实体类
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put(NormalExcelConstants.CLASS, ContractVo.class);
        map.put(NormalExcelConstants.PARAMS, new ExportParams("合同明细", "合同明细", ExcelType.XSSF));
        map.put(NormalExcelConstants.DATA_LIST, listOfSheet);
        dataList.add(map);

        SimpleDateFormat format = new SimpleDateFormat("MMddHHmm");
        String fileName = "CONTRACT_".concat(format.format(new Date()));
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, fileName);
        mv.addObject(NormalExcelConstants.MAP_LIST, dataList);
        return mv;
    };

    @Override
    public WmContract queryByBachNo(String batchNo){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmContract::getBatchNo, batchNo).last("LIMIT 1");;
        WmContract wmContract = getOne(queryWrapper);
        return wmContract;
    };

    @Override
    public List<WmContract> listByProject(WmProject wmProject){
        LambdaQueryWrapper<WmContract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmContract::getWmProjectId, wmProject.getId());
        return list(queryWrapper);
    };

    @Override
    public void executeContract(WmContract wmContract){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //合同最小销售单位
        List<WmContractProduct> wmContractProductList = contractProductMapper.selectLeafNodeContractProduct(wmContract.getId());
        for(WmContractProduct wmContractProduct: wmContractProductList){
            WmPlan wmPlanExist = planMapper.findByContractProduct(wmContractProduct.getId());//是否已经生成过计划
            if(wmPlanExist == null){
                WmPlan wmPlan = new WmPlan();
                wmPlan.setName(wmContractProduct.getName());
                wmPlan.setContractProductId(wmContractProduct.getId());
                wmPlan.setCurrentUserId(sysUser.getId());
                wmPlan.setPid(UserConstant.ZERO);
                wmPlan.setHasChild(UserConstant.SYS_NO);
                wmPlan.setPlanStatus(UserConstant.PLAN_STATUS_PREPARE);
                wmPlan.setPlanUserId(sysUser.getId());
                planMapper.insert(wmPlan);

                WmPlanLog wmPlanLog = new WmPlanLog();
                wmPlanLog.setWmPlanId(wmPlan.getId());
                wmPlanLog.setUserId(sysUser.getId());
                wmPlanLog.setMemo("创建计划");
                planLogMapper.insert(wmPlanLog);
            }
        }
    };
}
